// parse utils
export function param2Obj(url) {
  const search = url.split('?')[1];
  if (!search) {
    return {};
  }
  return JSON.parse(`{"${
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')}"}`);
}
// sessionStorage utils
const keyPrefix = 'WT-CORE-';
export function getSessionItem(key) {
  return JSON.parse(sessionStorage.getItem(`${keyPrefix}${key}`));
}

export function setSessionItem(key, params) {
  sessionStorage.setItem(`${keyPrefix}${key}`, JSON.stringify(params));
}

export function removeSessionItem(key) {
  sessionStorage.removeItem(`${keyPrefix}${key}`);
}

export function clearSessionItems() {
  sessionStorage.clear();
}
// user utils
const USERINFO = 'userinfo';
export function getCacheUser () {
  return getSessionItem(USERINFO);
}
export function setCacheUser (cacheUser) {
  setSessionItem(USERINFO, cacheUser);
}

export function hasPermission (roles, route) {
  if (route && route.roles) {
    return roles.some(role => route.roles.indexOf(role) >= 0);
  } else {
    return true;
  }
}

// 此解析法对于new Date等类型非常不友好
export function deepCopy (origin) {
  if (typeof origin === 'object') {
    return JSON.parse(JSON.stringify(origin));
  } else {
    return origin;
  }
}
